import { ELEMENT_TYPES } from '../constants/ActionTypes';
//判断元素是否为E9改造后的元素
const isE9Element = (ebaseid) => {
    for(var key in ELEMENT_TYPES){
        if(ebaseid === ELEMENT_TYPES[key]) return true;
    }
    return false;
}

//无权访问的元素的组件
class NoRightCom extends React.Component{
	render(){
		const style = { width: '100%', height: '160px', textAlign: 'center', paddingTop: '63px' };  
		return <div style = {style}>
    			<img src="/synergy/js/waring_wev8.png" />{"对不起，您暂时没有权限！"}
   		 	</div>
	}
}

//处理计算E9元素高度
const handleHeight = (oldstyle) => {
    let style = {};
    if(!_isEmpty(oldstyle)){
        style = {...oldstyle};
    	if(style.height){
	        const height = style.height.replace("px","");
	        let nherght = parseInt((parseInt(height) -32 +1 )/25) * 31 + 32;
	       	style['height'] = nherght+'px';
	    }
    }
    return style;
}

//返回前一个tab
const doPrev = (eid) => {
    $("#tabContainer_"+eid).scrollTo( {top:'0px',left:($("#tabContainer_"+eid).get(0).scrollLeft - 77 + 'px')}, 500 );
}

//进入下一个tab
const doNext = (eid) => {
    $("#tabContainer_"+eid).scrollTo( {top:'0px',left:($("#tabContainer_"+eid).get(0).scrollLeft + 77 + 'px')}, 500 );
}

//处理多tab的宽度，并判断是否显示左右箭头导航
const handleWidth = (eid, hpid, length, canHeadbar) => {
    var divWidth = length*77+36;
    var hpWidth = $("#content_"+eid).width();
    if(parseInt(hpid) < 0){
        var hpdom = $("#item_"+eid).parents("div[class='homepage']")[0];
        hpWidth = $(hpdom).parent().width();
        hpWidth = hpWidth - 20;
        divWidth = divWidth - 36;
    }       
    var titleWidth = hpWidth-10;
    if(!canHeadbar){
         hpWidth = hpWidth - $("#content_"+eid).find(".optoolbar").width();
    }
    if(parseFloat(divWidth) > parseFloat(hpWidth)) {
        $("#tabnavprev_"+eid).css("display","block");
        $("#tabnavnext_"+eid).css("display","block");
        if(length>1){
            if(!canHeadbar){
                $("#tabContainer_"+eid).css("width", hpWidth - 55);
                $("#tabnavnext_"+eid).css("right","110px");
            }else{
                $("#tabContainer_"+eid).css("width", hpWidth - 55);
                $("#titleContainer_"+eid).css("width", hpWidth);
            }
            $("#tabContainer_"+eid).css("display", ""); 
            $("#tabContainer_"+eid).css("margin-left", "0px");
            $("#tabContainer_"+eid).css("margin-right", "0px"); 
          }else{
            $("#tabnavprev_"+eid).css("display","none");
            $("#tabnavnext_"+eid).css("display","none");
            $("#tabContainer_"+eid).css("display", "none"); 
          }
        
    }else{
        $("#tabnavprev_"+eid).css("display","none");
        $("#tabnavnext_"+eid).css("display","none");
        if(length>1){
            if(!canHeadbar){
                $("#tabContainer_"+eid).css("width", hpWidth-50);
            }else{
                $("#tabContainer_"+eid).css("width", hpWidth);
            }
            $("#tabContainer_"+eid).css("display", ""); 
            $("#tabContainer_"+eid).css("margin-left", "0");
            $("#tabContainer_"+eid).css("margin-right", "0"); 
        }else{
         $("#tabContainer_"+eid).css("display", "none"); 
        }
    }
    $("#tabContainer_"+eid+" table").css("width", length*77);
}

//处理antd Table数据，返回columns
const formatData = (obj, esetting) => {
    const { imgSymbol, linkmode, isremind, widths, titles, ebaseid, eid } = esetting;
    const columns = new Array;
    var i = 0;
    //加载行小图标 
    if (imgSymbol) {
        const iObj = {
            dataIndex: 'imgSymbol',
            key: 'imgSymbol',
            width: '8',
            render: () => <img style={{marginBottom:'4px'}} name='esymbol' src={imgSymbol}/>
        }
        columns.push(iObj);
    }
    for (var k in obj) {
        var colObj = new Object;
        const kv = obj[k];
        if (typeof kv === 'object' && kv.constructor === Object) {       //判断属性值的类型，Object类型
            colObj = {
                dataIndex: k,
                className: ebaseid === ELEMENT_TYPES.WORKFLOW && k === 'requestname' ? 'reqdetail':'',
                key: k,
                render: (text) => loadRemind(text, linkmode, isremind)
            }
        } else if (typeof kv === 'object' && kv.constructor === Array) { //判断属性值的类型，List类型，建模查询中心元素用到                   
            colObj = {
                dataIndex: k,
                key: k,
                render: (text) => loadListName(text, linkmode)
            }
        } else {                                                         //判断属性值的类型，字符串类型 
            colObj = {
                dataIndex: k,
                key: k,
                render: (text) => {
                    if(typeof text === 'string'){
                        if (_isHtml(text)) {                                 //判断字符串是否含有html 
                            return <font className="font" dangerouslySetInnerHTML={{__html:text}}></font>
                        } else {
                            return <font className="font">{text}</font>
                        }
                    }else{
                        return <font className="font"></font>
                    }

                }
            }
        }
        if (titles) colObj['title'] = titles[i];
        if (widths) colObj['width'] = widths[i];
        columns.push(colObj);
        i += 1;
    }
    if (ebaseid === ELEMENT_TYPES.WORKFLOW) {                                               //加载流程签字意见查看小图标 
        const iObj = {
            dataIndex: '"imgdetail"',
            key: '"imgdetail"',
            width: '10',
            render: () => <img className="imgdetail" style={{cursor:'pointer',display:'none',marginLeft:'-8px',marginBottom:'-1px'}} src="/images/ecology8/homepage/req_wev8.png" width="12px" height="12px"/>
        }
        columns.push(iObj);
    }
    return columns;
}

//处理属性为集合的数据
const loadListName = (list, linkmode) => {
    if (!list || list.length === 0) return <span></span>
    let html = list.map((obj, o) => {
        var dotstr = o === 0 ? "" : " , ";
        if (obj.constructor === Object) {
            if (obj.userid) {
                var ahtml = "<a href='javascript:openhrm("+ obj.userid +");' onclick='pointerXY(event)' title="+obj.name+"><font style='color:#000000;' className={`font`}>"+obj.name+"</font></a>";
                return <span dangerouslySetInnerHTML={{__html:ahtml}}></span>
            }
            return <font>{dotstr}<a href="javascript:void(0);" onClick={openLinkUrl.bind(this, obj.link, linkmode)}><font className="font">{obj.name}</font></a></font>
        } else if (obj.constructor === Array) {
            let shtml = obj.map((sobj, s) => {
                if (sobj.userid) {
                    var ahtml = "<a href='javascript:openhrm("+ obj.userid +");' onclick='pointerXY(event)' title="+obj.name+"><font style='color:#000000;' className={`font`}>"+sobj.name+"</font></a>";
                    return <span dangerouslySetInnerHTML={{__html:ahtml}}></span>
                }
                return <a href="javascript:void(0);" onClick={openLinkUrl.bind(this, sobj.link, linkmode)}><font className={`font`}>{sobj.name}</font></a>
            });
            return <font>{dotstr}{shtml}</font>;
        }
    });
    return <span className="td-span-formmodecustomsearch">{html}</span>
}

//加载提醒方式
const loadRemind = (obj, linkmode, isremind) => {
    if (obj.userid) {
        var ahtml = "<a href='javascript:openhrm("+ obj.userid +");' onclick='pointerXY(event)' title="+obj.name+"><font style='color:#000000;' className={`font`}>"+obj.name+"</font></a>";
        return <span dangerouslySetInnerHTML={{__html:ahtml}}></span>
    }
    var nametitle = obj.name;
    if (obj.pretitle) nametitle = obj.pretitle + nametitle;
    if (obj.lasttitle) nametitle = nametitle + obj.lasttitle;
    var showName = <font dangerouslySetInnerHTML={{__html:obj.name}}></font>
    if (obj.img) {
        if (isremind) {
            var style = {};
            var tempremind = "";
            if (isremind.indexOf("#")> -1) {
                tempremind = isremind.substring(0, isremind.indexOf("#") - 1);
            } else {
                tempremind = isremind;
            }
            if (tempremind.indexOf("3") !== -1) {
                var color = isremind.substr(isremind.indexOf("#"));
                style['color'] = color + ' !important';
            }
            if (tempremind.indexOf("1") !== -1) {
                style['fontWeight'] = 'bold';
            }
            if (tempremind.indexOf("2") !== -1) {
                style['fontStyle'] = 'italic';
            }
            if (tempremind.indexOf("0") === -1) {
                return <span className="td-span"><a href="javascript:void(0);" onClick={openLinkUrl.bind(this, obj.link, linkmode)} data-link={obj.link} data-requestid={obj.requestid} title={nametitle}><font className="font"><font style={style}>{obj.pretitle?obj.pretitle:''}{showName}{obj.lasttitle?<b style={{fontWeight:'bold'}}>{obj.lasttitle}</b>:null}</font></font></a></span>
            } else {
                return <span className="td-span"><a href="javascript:void(0);" onClick={openLinkUrl.bind(this, obj.link, linkmode)} data-link={obj.link} data-requestid={obj.requestid} title={nametitle}><font className="font"><font style={style}>{obj.pretitle?obj.pretitle:''}{showName}{obj.lasttitle?<b style={{fontWeight:'bold'}}>{obj.lasttitle}</b>:null}</font></font>&nbsp;</a><img className="wfremindimg" src={obj.img}/></span>
            }
        }
        return <span className="td-span"><a href="javascript:void(0);" onClick={openLinkUrl.bind(this, obj.link, linkmode)} data-link={obj.link} data-requestid={obj.requestid} title={nametitle}><font className="font">{obj.pretitle?obj.pretitle:''}{showName}{obj.lasttitle?<b style={{fontWeight:'bold'}}>{obj.lasttitle}</b>:null}</font>&nbsp;</a><img className="wfremindimg" src={obj.img}/></span>
    }

    return <span className="td-span"><a href="javascript:void(0);" onClick={openLinkUrl.bind(this, obj.link, linkmode)} data-link={obj.link} data-requestid={obj.requestid} title={nametitle}><font className="font">{obj.pretitle?obj.pretitle:''}{showName}{obj.lasttitle?<b style={{fontWeight:'bold'}}>{obj.lasttitle}</b>:null}</font></a></span>
}


//获取当前时间戳(以s为单位)
const formatDate = function(_date, format) {
    var date = {
        "M+": _date.getMonth() + 1,
        "d+": _date.getDate(),
        "h+": _date.getHours(),
        "m+": _date.getMinutes(),
        "s+": _date.getSeconds(),
        "q+": Math.floor((_date.getMonth() + 3) / 3),
        "S+": _date.getMilliseconds()
    };
    if (/(y+)/i.test(format)) {
        format = format.replace(RegExp.$1, (_date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in date) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
        }
    }
    return format;
}

//数组contains函数
const isContain = function(arr, element) {  
    for (var i = 0; i < arr.length; i++) { 
        if (arr[i] == element) {  
            return true; 
        }
    }
    return false; 
} 

//定义map函数，实现间隔遍历
const intervalMap = function(arr, fn, mul = 1) {
    var a = [];
    for (var i = 0; i < arr.length; i += mul) {
        var value = fn(arr[i], i);
        if (value == null) {
            continue; //如果函数fn返回null，则从数组中删除该项
        }
        a.push(value);
    }
    return a;
};

//判断是否为空
const _isEmpty = function(value) {
    var type;
    if (value == null) { // 等同于 value === undefined || value === null
        return true;
    }
    type = Object.prototype.toString.call(value).slice(8, -1);
    switch (type) {
        case 'String':
            return !$.trim(value);
        case 'Array':
            return !value.length;
        case 'Object':
            return $.isEmptyObject(value); // 普通对象使用 for...in 判断，有 key 即为 false
        default:
            return false; // 其他对象均视作非空
    }
}


/** --------- 元素工具栏功能js函数 -----------**/

function onSetting(eid, ebaseid, hpid, subCompanyId) {
  // 获取设置页面内容
  var settingUrl = "/page/element/setting.jsp"
    + "?eid="+ eid
    + "&ebaseid="+ ebaseid
    + "&hpid=" + hpid
    + "&subcompanyid=" + subCompanyId;
    $.post(settingUrl, null, function(data) {
    if ($.trim(data) != "") {
      $("#setting_" + eid).hide();
      $("#setting_" + eid).remove();
      $("#content_" + eid).prepend($.trim(data));
      
      $(".tabs").PortalTabs({
        getLine : 1,
        topHeight : 40
      });
      $(".tab_box").height(0);
      
      $("#setting_" + eid).show();
      $("#weavertabs-content-" + eid).show();
      var urlContent = $.trim($("#weavertabs-content-" + eid).attr("url")).replace(/&amp;/g, "&");
      var urlStyle = $.trim($("#weavertabs-style-" + eid).attr("url")).replace(/&amp;/g, "&");
      var urlShare = $.trim($("#weavertabs-share-" + eid).attr("url")).replace(/&amp;/g, "&");
      if (urlContent != "") {
        var randomValue = new Date().getTime();
        
        if (ebaseid == 7 || ebaseid == 8 || ebaseid == 1 || ebaseid == 'news' || ebaseid == 29 || ebaseid == 'reportForm') {
          $("#setting_" + eid).attr("randomValue", randomValue);
        }
        
        urlContent = urlContent + "&random=" + randomValue;

        $("#weavertabs-content-" + eid).html("")
        $("#weavertabs-content-" + eid).html("<img src=/images/loading2_wev8.gif> loading...");
        $("#weavertabs-content-" + eid).load(urlContent, {}, function() {
          //$("#sync_datacenter_"+eid).tzCheckbox({labels:['','']});
          $(".filetree").filetree();
            //$(".vtip").simpletooltip();
          //fixedPosition(eid);
          jscolor.init();
          // 初始化layout组件
          initLayout();
        });
      }
      if (urlStyle != "") {
        $("#weavertabs-style-" + eid).load(urlStyle, {}, function() {
          // 初始化layout组件
          initLayout();
          $("#weavertabs-style-" + eid).hide();
        });
      }
      if (urlShare != "") {
        $("#weavertabs-share-" + eid).load(urlShare, {}, function() {
          $("#weavertabs-share-" + eid).hide();
        });
      }
    }
  });
}

const openMoreWin = function(eid, event){
    var dom = event.currentTarget;
    var moreurl = $("#more_" + eid).attr("data-morehref");
    if (!moreurl) return;
    if (moreurl.indexOf('/main/workflow/queryFlow') === -1) {
        var tabid = $("#titleContainer_" + eid).find("td[class='tab2selected']").attr("data-tabid");
        if (tabid)
            moreurl += '&tabid=' + tabid
    }
    openLinkUrl(moreurl, '2');
}

//获取html自定义属性名称
const handleAttr = function(attr, layoutid = $(".homepage").attr("data-layoutid")){
    var arr = ['1','2','3','4','5']; 
    if(isContain(arr, layoutid)){
        return "data-"+attr;
    }else{
        return attr;
    }
}

const _s2Int = function(s) {
    return _str2Int(s, -1);
}

const _str2Int = function(s, def) {
    return isNaN(parseInt(s)) ? (isNaN(parseInt(def)) ? -1 : parseInt(def)) : parseInt(s);
}

const _isHtml = function(htmlStr) {  
  if(!htmlStr) return false;
  var reg = /<[^>]+>/g;  
  return reg.test(htmlStr) || htmlStr.indexOf("&")>-1;  
} 

const openLinkUrl = function(url, linkmode,event) {
    if (event != undefined) {
        var domobj = event.currentTarget;
        var imgObj = $(domobj).closest('span').find("img");
        var fontObj = $(domobj).closest('span').find("font");
        $(imgObj).css("display", "none");
    }
    if (!url) return;
    var index = url.indexOf("/main/workflow/req");
    if(index !== -1){
        openSPA4Single(url);
        return;
    }
    if (index === -1) {
        linkmode = '2';
    }
    switch (linkmode) {
        case '1':
            if (index !== -1)
                weaHistory.push({
                    pathname: url
                });
            else
                window.location.href = url;
            break;
        case '2':
            var redirectUrl = url;
            var width = screen.availWidth;
            var height = screen.availHeight;
            var szFeatures = "top=0,";
            szFeatures += "left=0,";
            if (url.indexOf("ebaseid=15") != -1) {
                //td61285
                //szFeatures +="width=800," ;
                szFeatures += "width=" + (width - 10) + ",";
            } else {
                szFeatures += "width=" + (width - 10) + ",";
            }
            szFeatures += "height=" + (jQuery.browser.msie ? height : (height - 60)) + ",";
            szFeatures += "directories=no,";
            szFeatures += "status=yes,";
            szFeatures += "menubar=no,";
            szFeatures += "scrollbars=yes,";
            szFeatures += "resizable=yes";
            window.open(redirectUrl, "", szFeatures);
            break;
        default:
            window.open(url);
            break;
    }
}
function onShowOrHideE(eid){    
    $("#content_"+eid).toggle();
}

module.exports = {
    NoRightCom,
    handleHeight,
    doPrev,
    doNext,
    handleWidth,
    isE9Element,
    formatData,
    loadRemind,
    formatDate,
    isContain,
    intervalMap,
    _isEmpty,
    onSetting,
    handleAttr,
    _s2Int,
    _str2Int,
    openMoreWin,
    openLinkUrl,
    onShowOrHideE
}





